#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2021/6/10 13:50
# @Author  : fuchen'en
# @Description:
import pika
import time

credentials = pika.PlainCredentials('test', 'test123')
parameters = pika.ConnectionParameters(host='10.0.20.66',
                                       port='5672',
                                       virtual_host='/',
                                       credentials=credentials)
connection = pika.BlockingConnection(parameters)
channel = connection.channel()

# 由于不知道是生产者先运行还是消费者先运行，所以需要重复声明队列，声明多次同一名称队列，只会生成一个
channel.queue_declare('task_queue', durable=True)


# 当获取到消息时，pika库会调用这个回调函数
def callback(ch, method, properties, body):
    print(" [x] Received {!r}".format(body.decode()))
    # 通过sleep来表示一个耗时任务
    time.sleep(body.count(b'.'))
    print(" [x] Done")
    ch.basic_ack(delivery_tag=method.delivery_tag)  # 手动发送消息确认（message acknowledgments）


# 告诉RabbitMQ公平分配任务，如果有忙碌的worker和闲置的worker，优先安排闲置的，也就是每个worker分配的任务最多一个
# basic_qos是一种协议
channel.basic_qos(prefetch_count=1)

# 告诉RabbitMQ这个回调函数会从名为“hello”的队列中接收消息。
# auto_ack为False在调用callback函数时，未收到确认标识，消息会重回队列。True，无论调用callback成功与否，消息都被消费掉。默认为False
channel.basic_consume(queue='hello', on_message_callback=callback)

print(' [*] Waiting for messages. To exit press CTRL+C')

# 等待接收消息
channel.start_consuming()
